<!--
 * @Description: 事件代理
 * @Author: rendc
 * @Date: 2021-09-09 09:06:32
 * @LastEditors: rendc
 * @LastEditTime: 2021-09-09 09:32:56
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>事件代理</title>
  <style>
    .parent {
      border: 1px solid blue;
      overflow: hidden;
    }

    .child {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      float: left;
      margin: 10px;
    }

    .add {
      width: 100px;
      height: 100px;
      border: 1px solid blue;
      float: left;
      margin: 10px;
      text-align: center;
      line-height: 100px;
    }
  </style>
</head>

<body>
  <div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="add" onclick="addChild()">+</div>
  </div>
</body>
<script>
  // 单个子元素绑定事件
  // var child = document.getElementsByClassName("child")[0];
  // child.onclick = function () {
  //   alert("我是子元素")
  // }
  // 多个子元素绑定事件
  // var child = document.getElementsByClassName("child");
  // for (let i = 0; i < child.length; i++) {
  //   child[i].onclick = function () {
  //     alert("我是子元素")
  //   };
  // }
  // 将事件代理到父元素上-事件代理
  var parent = document.getElementsByClassName('parent')[0];
  parent.onclick = function (event) {
    if (event.target.className === 'child') {
      alert("我是子元素")
    }
  }
  // 追加节点
  function addChild() {
    var parent = document.getElementsByClassName('parent')[0];
    var child = document.getElementsByClassName('child')[0];
    var cloneChild = child.cloneNode(true);
    var lastChild = parent.lastChild.previousSibling;
    // parent.appendChild(cloneChild);
    parent.insertBefore(cloneChild, lastChild);
  }
</script>

</html>